package com.kaikai.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kaikai.edu.entity.EduSubject;
import com.kaikai.edu.entity.ExcelSubjectData;
import com.kaikai.edu.service.EduSubjectService;
import com.kaikai.servicebase.exceptionhandler.MyException;

import java.util.Map;

public class ExcelListener extends AnalysisEventListener<ExcelSubjectData> {
    //由于要存入数据库中,所有需要serviceImpl对象,而此类不能交给spring管理,所以serviceImpl对象无法注入
    //需参数传入
    //由此创建有参构造方法
    private EduSubjectService eduSubjectService;
    public ExcelListener(){

    }
    public ExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService=eduSubjectService;

    }



    //判断一级标题不能重复添加
    //查询数据库,如果存在此一级分类,返回该分类,不存在返回null
    private EduSubject oneExistSubject(String name){
        //select * from edu_subject where title=? and parent='0'
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", 0);
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }

    //判断耳二级分类不能重复添加
    private EduSubject twoExistSubject(String name,String pid){
        //select * from edu_subject where title=? and parent=id'
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }


    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        //先判断传入是否为空

        if(excelSubjectData==null){
            throw new MyException(20001,"你的excel表格为空");
        }

        //一行一行读取,每次读取有两个值 一级分类和二级分类


        //1.存入一级类别
        String oneSubjectName=excelSubjectData.getOneSubjectName();
        EduSubject oneExistSubject = this.oneExistSubject(oneSubjectName);
        if(oneExistSubject==null){//没有相同的
            oneExistSubject=new EduSubject();
            oneExistSubject.setParentId("0");
            oneExistSubject.setTitle(oneSubjectName);
            eduSubjectService.save(oneExistSubject);
        }
        String pid=oneExistSubject.getId();
        //2.存入二级类别
        String twoSubjectName = excelSubjectData.getTwoSubjectName();
        EduSubject twoExistSubject = this.twoExistSubject(twoSubjectName, pid);
        if(twoExistSubject==null){
            twoExistSubject=new EduSubject();
            twoExistSubject.setTitle(twoSubjectName);
            twoExistSubject.setParentId(pid);
            eduSubjectService.save(twoExistSubject);
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息:"+headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
